//
//  DLQRCodeViewController.m
//  DLQRCodeExample
//
//  Created by liyan on 2016/12/20.
//  Copyright © 2016年 liyan. All rights reserved.
//

#import "DLQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>

#define KScanMargin 40
#define KScanW 100

@interface DLQRCodeViewController ()<AVCapturePhotoCaptureDelegate>
{
    AVCaptureSession *_session;
    AVCaptureVideoPreviewLayer *_previewLayer;
    
    UIView  *_scanWindow;
    UIImageView *_scanGrid;
}
@end

@implementation DLQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    
    [self setupScanWindow];
    
    [self getCaotureDevice];
    
    [self resumeAnimation];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self maskLayer];
}

- (void)maskLayer{

    UIView *maskeView = [[UIView alloc] initWithFrame:self.view.bounds];
    [maskeView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.4]];
    
    [self.view addSubview:maskeView];
    
}

- (void)setupScanWindow{
    
    CGFloat scanWindowW = KScreenW - KScanMargin*2;
    CGFloat scanWindowH = KScreenW - KScanMargin*2;
    
    
    _scanWindow = [[UIView alloc] initWithFrame:CGRectMake(KScanMargin, KScanW, scanWindowW, scanWindowH)];
    _scanWindow.clipsToBounds = YES;
    [self.view addSubview:_scanWindow];
 
    UIImageView *scanGrid = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scanGrid"]];
    scanGrid.contentMode = UIViewContentModeScaleToFill;
    _scanGrid = scanGrid;
    CGFloat cornerH = 18;
    
    UIImageView *topLeftImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cornerH, cornerH)];
    topLeftImg.image = [UIImage imageNamed:@"QRCodeTopLeft"];
    
    UIImageView *topRightImg = [[UIImageView alloc] initWithFrame:CGRectMake(scanWindowW - cornerH, 0, cornerH, cornerH)];
    topRightImg.image = [UIImage imageNamed:@"QRCodeTopRight"];
    
    UIImageView *bottomLeftImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, scanWindowH-cornerH, cornerH, cornerH)];
    bottomLeftImg.image = [UIImage imageNamed:@"QRCodebottomLeft"];
    
    UIImageView *bottomRightImg = [[UIImageView alloc] initWithFrame:CGRectMake(scanWindowH-cornerH, scanWindowH-cornerH, cornerH, cornerH)];
    bottomRightImg.image = [UIImage imageNamed:@"QRCodebottomRight"];
    
    [_scanWindow addSubview:topLeftImg];
    [_scanWindow addSubview:topRightImg];
    [_scanWindow addSubview:bottomLeftImg];
    [_scanWindow addSubview:bottomRightImg];
    
    
}

- (void)getCaotureDevice{

    //获取摄像设备->创建输入流->创建输出流->设置代理,主线程里刷新->设置有效扫描区域->初始化链接对象
    //高质量采集率
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    CGRect rectInterest = [self setScanRect:_scanWindow.frame WithBounds:self.view.bounds];
    
    output.rectOfInterest = rectInterest;
    //output.rectOfInterest = CGRectMake(0.05, 0.2, 0.7, 0.6);
    //初始化链接对象
    _session = [[AVCaptureSession alloc] init];
    //高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    [_session addInput:deviceInput];
    [_session addOutput:output];
    
    //设置扫描编码格式 二维码、商品条形码
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeEAN8Code];
    
    // 实例化预览图层, 传递_session是为了告诉图层将来显示什么内容
    _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _previewLayer.frame = self.view.bounds;
    
    // 将图层插入当前视图
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    //开始捕获
    [_session startRunning];
    
    
}

- (CGRect)setScanRect:(CGRect)rect WithBounds:(CGRect)boudsRect{

    CGFloat rectWidth = rect.size.width;
    CGFloat rectHeight = rect.size.height;
    CGFloat boudsWidth = boudsRect.size.width;
    CGFloat boudsHeight = boudsRect.size.height;
    
    
    CGFloat x = (boudsWidth - rectWidth)/2 / boudsWidth;
    CGFloat y = (boudsHeight - rectHeight)/2 / boudsHeight;
    CGFloat width = rectHeight / boudsHeight;
    CGFloat height = rectWidth / boudsWidth;
    
    return CGRectMake(x, y, width, height);
    
}

- (void)resumeAnimation{

    CAAnimation *animtion = [_scanGrid.layer animationForKey:@"translationAnimation"];
    if (animtion) {
        
        // 1. 将动画的时间偏移量作为暂停时的时间点
        CFTimeInterval pauseTime = _scanGrid.layer.timeOffset;
        // 2. 根据媒体时间计算出准确的启动动画时间，对之前暂停动画的时间进行修正
        CFTimeInterval beginTime = CACurrentMediaTime() - pauseTime;
        
        // 3. 要把偏移时间清零
        [_scanGrid.layer setTimeOffset:0.0];
        // 4. 设置图层的开始动画时间
        [_scanGrid.layer setBeginTime:beginTime];
        
        [_scanGrid.layer setSpeed:1.0];
        
        [_scanGrid.layer removeAnimationForKey:@"translationAnimation"];
        
        
    }else{
        CGFloat scanWindowW = KScreenW - KScanMargin*2;
        CGFloat scanWindowH = KScreenW - KScanMargin*2;
        _scanGrid.frame = CGRectMake(0, -scanWindowH, scanWindowW, scanWindowH);
        
        CABasicAnimation *baseAnimation = [CABasicAnimation animation];
        baseAnimation.keyPath = @"transform.translation.y";
        baseAnimation.byValue = @(scanWindowH);
        baseAnimation.duration = 4.0;
        baseAnimation.repeatCount = MAXFLOAT;
        [_scanWindow addSubview:_scanGrid];
        [_scanGrid.layer  addAnimation:baseAnimation forKey:@"translationAnimation"];
    }
    
    
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

    if (metadataObjects.count>0) {
        [_session stopRunning];
        [self resumeAnimation];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        UIAlertAction *aginScan = [UIAlertAction actionWithTitle:@"再次扫描" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_session startRunning];
            [self resumeAnimation];
        }];
        
        UIAlertAction *outScan = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"扫描结果" message:[metadataObject stringValue] preferredStyle:UIAlertControllerStyleActionSheet];
        [alerController addAction:aginScan];
        [alerController addAction:outScan];
        
        [self presentViewController:alerController animated:YES completion:nil];
        
      
    }

}


@end
